package com.party.web.web.controller.gatherForm;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.gatherForm.*;
import com.party.core.service.gatherForm.IGatherFormInfoService;
import com.party.core.service.gatherForm.IGatherFormOptionService;
import com.party.core.service.gatherForm.IGatherFormService;
import com.party.core.service.gatherForm.IGatherProjectService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.biz.file.FileBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.gatherForm.GatherProjectOutput;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 表单项目
 *
 * @author Administrator
 */
@Controller
@RequestMapping("gatherForm/project")
public class GatherProjectController {
    @Autowired
    private IGatherProjectService gatherProjectService;
    @Autowired
    private IGatherFormInfoService gatherFormInfoService;
    @Autowired
    private IGatherFormOptionService gatherFormOptionService;
    @Autowired
    private IGatherFormService gatherFormService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;
    @Autowired
    private IMemberGroupService memberGroupService;

    protected static Logger logger = LoggerFactory.getLogger(GatherProjectController.class);

    @RequestMapping("list")
    public ModelAndView list(GatherProject gatherProject, CommonInput commonInput, Page page) throws Exception {
        page.setLimit(20);
        String memberId = RealmUtils.getCurrentUser().getId();
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        List<String> orgIds = memberGroupService.getChildWithMy(memberId);
        params.put("orgIds", orgIds);
        List<GatherProject> gatherProjects = gatherProjectService.webListPage(gatherProject, params, page);
        List<GatherProjectOutput> outputs = Lists.newArrayList();

        for (GatherProject input : gatherProjects) {
            String filePath = fileBizService.getUploadCIPath(input.getCreateBy(), "gatherForm");
            GatherProjectOutput output = new GatherProjectOutput();
            MyBeanUtils.copyBeanNotNull2Bean(input, output);
            output.setTotalNum(input.getQuantity());

            // 二维码
            String baseQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + input.getId());
            output.setQrCodeUrl(baseQrCodeUrl);
            outputs.add(output);
        }

        ModelAndView mv = new ModelAndView("gatherForm/projectList");
        mv.addObject("gatherProjects", outputs);
        mv.addObject("project", gatherProject);
        mv.addObject("input", commonInput);
        mv.addObject("page", page);
        return mv;
    }
    @DataControl
    @RequestMapping("toForm")
    public ModelAndView toForm(@ControlParam(table = "gather_d_project", column = "create_by", isRequired = false)String id) {
        ModelAndView mv = new ModelAndView("gatherForm/projectForm");
        if (StringUtils.isNotEmpty(id)) {
            GatherProject gatherProject = gatherProjectService.get(id);
            if (StringUtils.isNotEmpty(gatherProject.getContent())) {
                String content = StringUtils.unescapeHtml4Video2Iframe(gatherProject.getContent());
                gatherProject.setContent(content);
            }
            mv.addObject("project", gatherProject);
            Map<String, Object> resultMap = gatherProjectBizService.getFormItems(gatherProject.getId(), gatherProject.getQuantity());
            mv.addAllObjects(resultMap);
        }
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(GatherProject gatherProject, BindingResult result) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            return AjaxResult.error(allErros.get(0).getDefaultMessage());
        }
        try {
            List<String> newFieldIds = Lists.newArrayList();

            if (StringUtils.isNotEmpty(gatherProject.getContent())) {
                String content = StringUtils.escapeHtml4Iframe2Video(gatherProject.getContent().trim());
                gatherProject.setContent(content);
            }

            String projectId = gatherProject.getId();
            String currentId = RealmUtils.getCurrentUser().getId();
            if (StringUtils.isEmpty(gatherProject.getShowPicture())) {
                gatherProject.setShowPicture("1");
            }
            if (StringUtils.isNotEmpty(gatherProject.getId())) {
                GatherProject t = gatherProjectService.get(gatherProject.getId());
                MyBeanUtils.copyBeanNotNull2Bean(gatherProject, t);
                gatherProjectService.update(t);

                currentId = t.getCreateBy();
            } else {
                // 默认不通知
                gatherProject.setIsRemindMe("2");
                gatherProject.setCreateBy(currentId);
                gatherProject.setUpdateBy(currentId);
                projectId = gatherProjectService.insert(gatherProject);

                if (StringUtils.isNotEmpty(gatherProject.getShowResource()) && gatherProject.getShowResource().equals("1")) {
                    GatherForm newGatherForm = new GatherForm();
                    GatherForm newGatherForm2 = new GatherForm();
                    newGatherForm.setCategory(Constant.FIELD_RESOURCE);
                    newGatherForm.setTitle("来源");
                    newGatherForm.setType("input");
                    newGatherForm.setProjectId(projectId);
                    newGatherForm.setDescription("请输入来源");
                    newGatherForm.setRequired("false");
                    newGatherForm.setSort(-1);

                    newGatherForm2.setCategory(Constant.FIELD_RESOURCELINK);
                    newGatherForm2.setTitle("来源链接");
                    newGatherForm2.setType("input");
                    newGatherForm2.setProjectId(projectId);
                    newGatherForm2.setDescription("请输入来源链接");
                    newGatherForm2.setRequired("false");
                    newGatherForm2.setSort(0);
                    gatherFormService.insert(newGatherForm);
                    gatherFormService.insert(newGatherForm2);

                    newFieldIds.add(newGatherForm.getId());
                    newFieldIds.add(newGatherForm2.getId());
                }
            }
            gatherProjectBizService.saveFormItems(gatherProject.getItems(), projectId, currentId, newFieldIds);

            try {
                String filePath = fileBizService.getUploadCIPath(currentId, "gatherForm");
                String content = "gather_form/form_info.html?projectId=" + gatherProject.getId();
                fileBizService.uploadCloudOut(gatherProject.getId(), filePath, content, currentId);
            } catch (Exception e) {
                logger.error("生成表单二维码异常", e);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存项目异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除项目
     *
     * @param id 项目id
     * @return
     */
    @DataControl
    @ResponseBody
    @RequestMapping("delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(@ControlParam(table = "gather_d_project", column = "create_by")String id) {
        try {
            List<GatherFormInfo> infos = gatherFormInfoService.list(new GatherFormInfo(id));
            if (infos.size() > 0) {
                return AjaxResult.error("已有收集信息，不能删除");
            }
            List<GatherForm> fields = gatherFormService.list(new GatherForm(id));
            for (GatherForm gatherForm : fields) {
                gatherFormOptionService.deleteByField(gatherForm.getId());
            }
            gatherFormService.deleteByProject(id);
            gatherProjectService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除项目异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除项目异常");
        }
    }

    /**
     * 项目详情
     *
     * @param projectId 项目id
     * @return
     */
    @ResponseBody
    @RequestMapping("getDetails")
    public AjaxResult getDetails(String projectId) {
        if (StringUtils.isEmpty(projectId)) {
            return AjaxResult.error("项目id不能为空");
        }
        GatherProject gatherProject = gatherProjectService.get(projectId);
        if (null == gatherProject || gatherProject.getDelFlag().equals("1")) {
            return AjaxResult.error("信息收集项目不存在");
        }
        if (StringUtils.isNotEmpty(gatherProject.getContent())) {
            String content = StringUtils.unescapeHtml4Video2Iframe(gatherProject.getContent());
            gatherProject.setContent(content);
        }

        GatherForm t = new GatherForm();
        t.setProjectId(projectId);
        List<GatherForm> gatherForms = gatherFormService.list(t);
        for (GatherForm gatherForm : gatherForms) {
            if (gatherForm.getType().equals(FormType.CHECKBOX.getValue()) || gatherForm.getType().equals(FormType.RADIO.getValue())
                    || gatherForm.getType().equals(FormType.SELECT.getValue())) {
                List<GatherFormOption> subitems = gatherFormOptionService.list(new GatherFormOption(gatherForm.getId()));
                gatherForm.setSubitems(subitems);
            }
        }
        gatherProject.setItems(gatherForms);
        return AjaxResult.success(gatherProject);
    }
}
